#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, os, re, ConfigParser
from optparse import OptionParser
import shutil
import projectx,encoder, chapters
from common import *
from logger import Logger
import globals
import config
from createmkv import createmkv
from srtadjust import adjust_srt

def main():
    optionparser = OptionParser(usage = "%prog [options] <file1> <file2> <file3> ...")
    availableoptions = config.settings
    for o in availableoptions:
        optionparser.add_option("--%s" % (o), dest = o, help="override %s" % (o), default = availableoptions[o])
    optionparser.add_option("--projectx", help="launch projectx", action="store_true", default = False)
    options, fnames = optionparser.parse_args()
    fnames = expandWildcards(fnames)
    if len(fnames) == 0:
        if options.projectx:
            colourstableexists = os.path.exists(os.path.join(os.getcwd(), 'colours.tbl'))
            if not colourstableexists:
                shutil.copy(os.path.join(config.projectXDir, 'colours.tbl'), os.getcwd())
            os.system('java -jar "%s" -ini "%s" -gui' % (os.path.join(config.projectXDir, 'ProjectX.jar'), os.path.join(config.configDir, 'X.ini')))
            if not colourstableexists:
                os.remove('colours.tbl')
        else:
            optionparser.error("no files given")
    else:
        for f in fnames:
            if not os.path.isfile(f):
                optionparser.error("file not found: " + f)

    overrides = vars(options)
    for option in overrides:
        config.settings[option] = overrides[option]

    createChapters = config.settings['mkvchapters'] in ['1', 'true', 'enabled', 'enable']

    videoEncodingOptions = config.getPresetData(config.settings['videopreset'])

    for fname in fnames:
        if options.projectx:
            os.system('java -jar "%s" -ini "%s" -gui "%s"' % (os.path.join(config.projectXDir, 'ProjectX.jar'), os.path.join(config.configDir, 'X.ini'), os.path.join('.', fname)))
            continue
        baseName = os.path.splitext(os.path.split(fname)[1])[0]
        logger = Logger()
        logger.setlogfile(baseName+".batchfile")
        logger.log("#!/bin/bash\n")
        if not os.path.isfile(fname):
            logger.log("\n#Error: The source file no longer exists\n")
            continue
        #streams = projectx.getstreams(fname)
        streams = projectx.getstreamsx(fname)
        projectx.generateXini(baseName + '.X.ini', streams)

        pids = []
        for pid, s in streams.iteritems():
            if (s['type'] == 'Audio' and s.has_key('language') and s['language'] not in options.excludedaudiolanguages.split(',')) or \
               (s['type'] in ['Subpict.', 'Subtitle'] and s.has_key('language') and s['language'] not in options.excludedsubtitlelanguages.split(',')) or \
                s['type'] == 'Video' or s['type'] == 'Teletext':
                    pids.append(pid)

        projectx.demux(fname, pids, baseName + '.X.ini')

        demuxlog = projectx.getLogName(fname)
        streams = projectx.resolvefilenames(streams, demuxlog)
        mkvfiles = []
        for stream in streams.copy():
            s = streams[stream]
            if not s.has_key('fname'):
                continue
            if s['type'] == 'Video':
                fname = s['fname'][0] #TODO: Handle array correctly
                if config.settings['videopreset'] == 'no-encoding':
                    mkvfiles.append({'fname':fname})
                else:
                    output = fname + '.enc'
                    mkvfiles.append({'fname':output})
                    s['encodedfile'] = output
                    encoder.encodeVideo(fname, output, videoEncodingOptions)

                if createChapters:
                    videoLenInSec = chapters.getvideolengthinsec(output)
                    cfname = chapters.writeChapterFile(logger, baseName, 5, videoLenInSec)
                    streams['0xffff'] = {'type': 'Chapters', 'fname': [cfname]}
                    mkvfiles.append({'fname':cfname})

            elif s['type'] == 'Audio':
                if s.has_key('language') and s['language'] not in options.excludedaudiolanguages.split(','):
                    fname = s['fname'][0] #TODO: Handle array correctly
                    audioPreset = ''
                    audioEncodingOptions = None

                    if fname.find('.ac3') != -1 or (s.has_key('details') and s['details'].find('5.1') != -1):
                        audioPreset = config.settings['audio51preset']
                        audioEncodingOptions = config.getPresetData(config.settings['audio51preset'])
                    else:
                        audioPreset = config.settings['audiopreset']
                        audioEncodingOptions = config.getPresetData(config.settings['audiopreset'])

                    if audioPreset == 'no-encoding':
                        mkvfiles.append({'fname':fname, 'language':s['language']})
                    else:
                        audioCodec = audioEncodingOptions['audiocodec']
                        output = fname + '.' + audioCodec #TODO
                        mkvfiles.append({'fname':output, 'language':s['language']})
                        s['encodedfile'] = output
                        encoder.encodeAudio(fname, output, audioEncodingOptions)
            elif s['type'] in ['Subpict.', 'Subtitle'] and config.settings['subtitlemode'] in ['dvb-text', 'both']:
                if s.has_key('language') and s['language'] not in options.excludedsubtitlelanguages.split(','):
                    for fname in s['fname']:
                        if fname.endswith('idx'):
                            mkvfiles.append({'fname':fname, 'language':s['language']})
            elif s['type'] == 'Teletext' and config.settings['subtitlemode'] in ['teletext', 'both']:
            	for page in s['pages']:
                    if page.has_key('language') and page['language'] not in options.excludedsubtitlelanguages.split(','):
                        for fname in s['fname']:
                            if fname.endswith('.srt'):
                                pagenum = re.search('.*\[(\d*)\].srt', fname).group(1)
                                if page['teletextpage'] == pagenum:
                                    adjust_srt(open(fname), open(fname + '.temp', 'w'), int(config.settings['teletexttimecorrection']))
                                    os.remove(fname)
                                    os.rename(fname + '.temp', fname)
                                    mkvfiles.append({'fname':fname, 'language':page['language']})

        createmkv(baseName + '.mkv', mkvfiles)

        logger.log('\n#Cleanup temporary files:\n')
        projectx.cleanup(streams, demuxlog)
        encoder.cleanup()

        logger.log("\n#Total duration %s\n" % (formatDuration(globals.totalDuration)))
        print "\nTotal duration %s\n" % (formatDuration(globals.totalDuration))

        globals.totalDuration = 0

if __name__ == '__main__':
    main()
